package com.alcj.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * @ClassName: CreateQrcUtil
 * @Description: 二维码生成工具类
 * @author chenxh
 * @date 2017年04月13日
 * @version V1.0
 */
public class SendServerUtil {

	public static final Logger logger = LoggerFactory.getLogger(SendServerUtil.class);
	
	/** 
     * 创建临时二维码 
     * @param
     * @return 
     */
	public static JSONObject getAccessToken() {
		try {

			URL url = new URL("http://localhost:8080/hello");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			connection.connect();

			OutputStream out = connection.getOutputStream();

			JSONObject jsonObj = JSONObject.parseObject("{}");
			
			logger.info("生成临时二维码参数： "+ jsonObj.toString().getBytes("UTF-8"));
			
			out.write(jsonObj.toString().getBytes("UTF-8"));
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}

			reader.close();
			// 断开连接
			connection.disconnect();
			
			logger.info("生成临时二维码结果： "+ sb.toString());
			
			JSONObject obj = JSONObject.parseObject(sb.toString());
			// 设定返回临时二维码图片
			obj.put("token", obj.get("token").toString());
			
			return obj;
		} catch (Exception e) {
			logger.error("生成临时二维码异常： "+ e.getMessage());
			logger.error("异常详细信息： "+ e);
		} 

		return null;
	}

	/** 
     * 创建永久二维码 生成二维码图片
     * @param token
     * @return 
     */
	public static JSONObject createLimitQrcode(String token,String sceneKey) {
		try {

			URL url = new URL("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			connection.connect();

			OutputStream out = connection.getOutputStream();

			String paramJson = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + sceneKey + "\"}}}";
			
			logger.info("生成二维码参数： "+ paramJson);
			
			JSONObject jsonObj = JSONObject.parseObject(paramJson);
			out.write(jsonObj.toString().getBytes("UTF-8"));
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}

			logger.info("生成二维码结果： "+ sb.toString());
			
			reader.close();
			// 断开连接
			connection.disconnect();

			JSONObject obj = JSONObject.parseObject(sb.toString());
			return obj;
		} catch (Exception e) {
			logger.error("生成二维码异常： "+ e.getMessage());
			logger.error("异常详细信息： "+ e);
		} 
		return null;
	}
	
	public static String getAccessToken(String appid, String appScret) throws Exception {
		try {
			// 获取公众号access_token
			URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appScret);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            
            connection.connect();
            
            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            
            JSONObject resultObj = JSONObject.parseObject(sb.toString());
            reader.close();
            // 断开连接
            connection.disconnect();
            
            return resultObj.get("access_token").toString();

		} catch (Exception e) {
			logger.error("获取token异常： "+ e.getMessage());
			logger.error("异常详细信息： "+ e);
		}

		return null;
	}
}
